<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1000px" @open="open" @close="close" :append-to-body="true" :modal-append-to-body="true">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit">
      <el-row>
        <el-col :span="12">
          <el-form-item label="任命类型" prop="appointmenttype" :rules="rules.validateRequire">
            <el-select v-model="model.appointmenttype" :disabled="true">
              <el-option v-for="item in codeModel.appointmenttypeList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序码" prop="sortcode">
            <el-input-number v-model="model.sortcode" controls-position="right" :step="1" :min="0" style="width:100%"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="usercode" :rules="rules.validateRequire">
            <tl-ref-user v-model="model.usercode" :initDisplayData.sync="model.username" dataType="code" :singleSelect="true" :disabled="model.candelete === 1"> </tl-ref-user>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工号" prop="usercode" :rules="rules.validateRequire">
            <el-input v-model="model.usercode" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="工作组名称" prop="workgroup">
            <el-input :disabled="true" v-model="model.workgroup"></el-input>
            <!-- <el-select v-model="model.workgroup" filterable clearable @change="clear()">
              <el-option v-for="item in codeModel.workgroupList" :key="item.code" :label="item.name"
                :value="item.code" />
            </el-select> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目角色" prop="projectrole" :rules="rules.validateRequire">
            <el-select v-model="model.projectrole" filterable clearable @change="clearDuty">
              <el-option v-for="item in projectRoleList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="职务" prop="position" :rules="rules.validateRequire">
            <el-input v-model="model.position"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="职责" prop="duty" :rules="rules.validateRequire" v-if="!dutySelect">
            <el-input v-model="model.duty" placeholder="负责***工作" :disabled="this.model.projectrole === '' || this.model.projectrole === undefined || this.model.projectrole === null || (this.grouptype > 0 && this.model.projectrole === 'groupleader')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="职责" prop="duty" :rules="rules.validateRequire" v-if="dutySelect">
            <el-select v-model="model.duty" filterable clearable multiple :disabled="this.model.projectrole === '' || this.model.projectrole === undefined || this.model.projectrole === null">
              <el-option v-for="item in projectDutyList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="具体职责" prop="detailduty" v-if="dutySelectLeader">
            <el-select v-model="model.detailduty" filterable clearable multiple :disabled="this.model.projectrole === '' || this.model.projectrole === undefined || this.model.projectrole === null" @change="detailDutyChange">
              <el-option v-for="item in projectDutyList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="具体内容" prop="moredetail" :rules="rules.validateRequire" v-if="editMoreDetail">
            <el-input v-model="model.moredetail" type="textarea" :placeholder="placeholderComp" maxlength="1000" show-word-limit :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="description">
            <el-input v-model="model.description" type="textarea" maxlength="1000" show-word-limit :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSaveAndCopy" :loading="saveLoading" v-if="isAdd === true">保存并复制</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="disableEditSubmit === false">确认 </el-button>
    </div>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_edit } from '@tapui/mixins/mixin_edit'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { validateNull } from '@tapui/utils/validate'
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: {},
  data() {
    return {
      moduleTitle: '项目任命-项目组成员',
      urlPrefix: '/mpm/projectTeam/',
      url: {
        // 额外的url
        queryCodeList: '/mpm/projectTeam/dataCodeList'
      },
      canEditWorkGroup: false,
      projectRoleList: []
    }
  },
  props: {
    parentId: {
      type: [Number, String],
      default: ''
    },
    projectCode: {
      type: [Number, String],
      default: ''
    },
    teamType: {
      type: [Number],
      default: 0
    },
    teamName: {
      type: String,
      default: ''
    },
    grouptype: {
      type: Number,
      default: NaN
    }
  },
  computed: {
    dutySelect() {
      return this.grouptype > 0 && this.model.projectrole === 'gruopworker'
    },
    dutySelectLeader() {
      return this.grouptype > 0 && this.model.projectrole === 'groupleader'
    },
    // 模板组组员选择职责包含其他、模板组组长选择具体职责包含其他，展示具体内容框，支持用户填写
    editMoreDetail() {
      return (this.dutySelect && !validateNull(this.model.duty) && this.projectDutyList.filter((item) => this.model.duty.includes(item.code)).filter((item) => item.name === '其他').length > 0) || (this.dutySelectLeader && !validateNull(this.model.detailduty) && this.projectDutyList.filter((item) => this.model.detailduty.includes(item.code)).filter((item) => item.name === '其他').length > 0)
    },
    placeholderComp() {
      return '负责***工作'
    },
    projectDutyList() {
      if (this.grouptype === 3) {
        return this.codeModel.businessRoleDutyList
      } else if (this.grouptype === 2) {
        return this.codeModel.bidGuideDutyList
      } else if (this.grouptype === 1) {
        return this.codeModel.bidBookDutyList
      } else {
        return []
      }
    }
  },
  methods: {
    /** 查询编码 */
    doQueryCode() {
      if (this.url.queryCodeList) {
        getAction(this.url.queryCodeList, {}).then((res) => {
          if (res.success) {
            this.codeModel = res.result
            if (this.codeModel.projectroleList && this.codeModel.projectroleList.length > 0) {
              this.projectRoleList = this.codeModel.projectroleList.filter((item) => item.code === 'gruopworker' || item.code === 'groupleader')
            }
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'appointdate', new Date())
        this.$set(this.model, 'applydate', new Date())
      }
      if (this.model.workgroup !== '') {
        this.canEditWorkGroup = true
      }
    },
    loaded() {
      // 页面加载完毕执行
      if (this.isAdd) {
        this.$set(this.model, 'projectcode', this.projectCode)
        this.$set(this.model, 'appointmentid', this.parentId)
        this.$set(this.model, 'appointmenttype', '1')
        this.$set(this.model, 'teamid', this.teamType)
        this.$set(this.model, 'workgroup', this.teamName)
        this.$set(this.model, 'grouptype', this.grouptype)
      }
    },
    doSaveAndCopy() {
      this.saveLoading = true
      this.$set(this.model, 'appointmentid', this.parentId)
      let isvalidate = true
      this.$refs.form.validate((valid) => {
        if (valid) {
        } else {
          isvalidate = false
        }
      })
      if (!isvalidate) {
        this.saveLoading = false
        return false
      }
      if (!this.beforeSubmit()) {
        return
      }
      // 增加唯一单号
      postAction(this.url.add + '?billuid=' + this.uid, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功,请继续添加', 'success')
            this.model = res.result
            this.$delete(this.model, 'id')
            this.$delete(this.model, 'usercode')
            this.$delete(this.model, 'username')
            this.$set(this.model, 'appointmenttype', '1')
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    // 当切换项目角色时，清空职责内容，如果三类模板任命组选择了组长，则赋值为xx工作组责任人且不可修改
    clearDuty() {
      this.$delete(this.model, 'duty')
      this.$delete(this.model, 'detailduty')
      this.$delete(this.model, 'moredetail')
      if (this.grouptype > 0 && this.model.projectrole === 'groupleader') {
        this.detailDutyChange()
      }
    },
    // 保存之前如果职责、具体职责字段为数组，转换为用逗号分割的字符串
    beforeSubmit() {
      if (Array.isArray(this.model.duty) && this.model.duty.length > 0) {
        this.$set(this.model, 'duty', this.model.duty.join(','))
      }
      if (Array.isArray(this.model.detailduty) && this.model.detailduty.length > 0) {
        this.$set(this.model, 'detailduty', this.model.detailduty.join(','))
      } else {
        this.$set(this.model, 'detailduty', null)
      }
      return true
    },
    // 保存之后，将职责字段转换为数组
    afterSubmit() {
      this.dutySelect ? this.$set(this.model, 'duty', this.model.duty.split(',')) : this.$set(this.model, 'duty', this.model.duty)
      this.model.detailduty ? this.$set(this.model, 'detailduty', this.model.detailduty.split(',')) : null
    },
    /** 编辑，发请求获得数据 */
    queryData(id) {
      if (!this.url.load) {
        this.$tap.alert('请设置load地址!', 'warning')
        return
      }
      return getAction(this.url.load, { id: id }).then((res) => {
        if (res.success) {
          this.model = res.result
          this.dutySelect ? this.$set(this.model, 'duty', this.model.duty.split(',')) : this.$set(this.model, 'duty', this.model.duty)
          this.model.detailduty ? this.$set(this.model, 'detailduty', this.model.detailduty.split(',')) : null
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    detailDutyChange() {
      let dutyStr = this.model.workgroup + '责任人'
      if (validateNull(this.model.detailduty)) {
      } else if (this.model.detailduty.length === 1) {
        dutyStr += '兼' + this.projectDutyList[this.model.detailduty[0] - 1].name + '工作'
      } else if (this.model.detailduty.length > 1) {
        let totalStr = '兼'
        this.model.detailduty.forEach((item, index) => {
          totalStr += (index + 1) + '、' + this.projectDutyList[item - 1].name + '；'
        })
        dutyStr += totalStr
      }
      this.$set(this.model, 'duty', dutyStr)
    }
  }
}
</script>
